﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using Tools;

namespace SharePointConnector
{
    public class Connector
    {
        /*

        #region Private Variables

        private string _siteUrl;
        private string _siteWeb;
        private string _userName;
        private string _password;
        private string _domain;

        #endregion

        #region Constructor

        public Connector(ISharePointConnectorModel details)
        {
            _siteUrl = details.SiteUrl;
            _siteWeb = "/";
            _userName = details.Username;
            _password = details.Password;
            _domain = details.Domain;
        }

        #endregion

        #region Private Methods

        #endregion

        #region Public Methods

        public bool ConnectViaImpersonator()
        {
            // Impersonate, automatically release the impersonation.
            using (new Impersonator(_userName, _domain, _password))
            {

                //string strUrl = "http://localhost:8099/";

                //var token = SPSite.RootWeb.EnsureUser("usernameToImpersonate").UserToken; 
                //using (SPSite site = new SPSite(token, this.ListAddress)) {   
                //    using (SPWeb web = site.OpenWeb())   {  
                //        // code here will be executed as selected user 
                //    } 
                //} 

                using (var site = new SPSite(_siteUrl))
                {
                    using (var web = site.OpenWeb())
                    {
                        foreach (SPList list in web.Lists)
                            Console.WriteLine(list.Title);
                    }
                }

                //var user = SPContext.Current.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
                //var superToken = user.UserToken;
                //using (var site = new SPSite(SPContext.Current.Web.Url, superToken))
                //{
                //    // This code runs under the security context of the SHAREPOINT\system
                //    // for all objects accessed through the "site" reference. Note that it's a 
                //    // different reference than SPContext.Current.Site. 
                //    using (var elevatedWeb = site.OpenWeb())
                //    {
                //        // Perform actions as SYSTEM here
                //    }
                //} 
            }
            return true;
        }

        private static SPUserToken GetSystemToken(SPSite spSite)
        {
            SPUserToken res = null;
            bool oldCatchAccessDeniedException = spSite.CatchAccessDeniedException;
            try
            {
                spSite.CatchAccessDeniedException = false;
                res = spSite.SystemAccount.UserToken;
            }
            catch (UnauthorizedAccessException)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite elevatedSPSite = new SPSite(spSite.ID))
                        res = elevatedSPSite.SystemAccount.UserToken;
                    // (***)
                });
            }
            finally
            {
                spSite.CatchAccessDeniedException = oldCatchAccessDeniedException;
            }
            return res;
        }

        public bool ConnectViaObjecModel()
        {
            SPUserToken res = null;
            using (var spSite = new SPSite(_siteUrl))
            {
                res = GetSystemToken(spSite);
            }

            using (var clientContext = new ClientContext(_siteUrl))
            {
                var credentialCache = new CredentialCache();

                if (_userName != null)
                {
                    // Use custom network credentials
                    var networkCredential = new NetworkCredential(_userName, _password, _domain);
                    credentialCache.Add(new Uri(_siteUrl), "Negotiate", networkCredential);
                }
                else
                {
                    // Use default network credentials
                    credentialCache.Add(new Uri(_siteUrl), "Negotiate", CredentialCache.DefaultNetworkCredentials);
                }

                clientContext.Credentials = credentialCache;
                Web web = clientContext.Web;
                ListCollection lists = web.Lists;
                IEnumerable<List> listCollection =
                    clientContext.LoadQuery(lists.Include(list => list.Title, list => list.Id,
                                                          list =>
                                                          list.Fields.Include(
                                                              field => field.Title,
                                                              field => field.InternalName)));
                clientContext.ExecuteQuery();

                var site = clientContext.Site;
                var user = site.RootWeb.EnsureUser("Contoso\administrator");
                //site.

                foreach (List list in listCollection.ToList())
                {
                    Console.WriteLine("Title is " + list.Title + ", ID is " + list.Id);
                    foreach (Field field in list.Fields)
                    {
                        Console.WriteLine("Field Title " + field.Title + " Internal Name " + field.InternalName);
                    }
                }
                Console.ReadLine();
            }


            //using (var clientContext = new ClientContext(_siteUrl))
            //{
            //    var credentialCache = new CredentialCache();

            //    if (_userName != null)
            //    {
            //        // Use custom network credentials
            //        var networkCredential = new NetworkCredential(_userName, _password, _domain);
            //        credentialCache.Add(new Uri(_siteUrl), "Negotiate", networkCredential);
            //    }
            //    else
            //    {
            //        // Use default network credentials
            //        credentialCache.Add(new Uri(_siteUrl), "Negotiate", CredentialCache.DefaultNetworkCredentials);
            //    }

            //    clientContext.Credentials = credentialCache;

            //    var site = clientContext.Site;
            //    var x = site.RootWeb.CurrentUser;

            //    // Load the web
            //    var web = clientContext.Web;
            //    clientContext.Load(web);
            //    clientContext.ExecuteQuery();

            //    // Load the sub-webs
            //    var webs = web.Webs;
            //    clientContext.Load(webs);
            //    clientContext.ExecuteQuery();

            //    Web subweb;

            //    if (!string.IsNullOrEmpty(_siteWeb))
            //    {
            //        subweb = Enumerable.FirstOrDefault(webs, t => t.ServerRelativeUrl == _siteWeb);

            //        if (subweb == null)
            //        {
            //            throw new Exception(
            //                string.Format("Unable to open sub-web: {0} from site: {1}", _siteWeb, _siteUrl));
            //        }
            //    }
            //    else
            //    {
            //        subweb = web;
            //    }

            //    // Load the specific sub-web
            //    clientContext.Load(subweb);
            //    clientContext.ExecuteQuery();

            //    // Get the list
            //    //var list = subweb.Lists.GetByTitle(listName);
            //    //spContext.Load(list);
            //    //spContext.ExecuteQuery();
            //}
            return true;
        }

        public bool ConnectViaAPI()
        {



            return true;
        }

        #endregion

        */
    }
}
